package com.du.method;


import com.du.enums.RenderSelectItem;

import java.util.*;


/**
 * @Desc :
 * @Author: shuangdu
 * @date : 2021/3/26
 */
public class Convert {

    private static Map<String, ConvertMethod> convertMap = new LinkedHashMap<>();

    public static void addConvertMap(String key, ConvertMethod method) {
        if (convertMap.containsKey(key)) {
            throw new RuntimeException("异常,不允许重复添加转换, key:" + key);
        }
        convertMap.put(key, method);
    }

    public static String sourceParse() {
        try {
            String item = ConvertContext.holder.getParam().getRenderSelectItem().toString();
            ConvertMethod convertMethod = convertMap.get(item);
            if (Objects.isNull(convertMethod)) {
                throw new RuntimeException("无对应转换器! item: " + item);
            }
            return convertMethod.parse();
        } catch (Exception e) {
            return errMsg(e);
        }
    }

    private static String errMsg(Exception e) {
        StringBuilder sb = new StringBuilder();
        for (StackTraceElement elem : e.getStackTrace()) {
            sb.append(elem.toString()).append("\n");
        }
        return sb.toString();
    }

    static {
        convertMap.put(RenderSelectItem.TO_MARKDOWN.toString(), new MysqlConvertMarkdown());
        convertMap.put(RenderSelectItem.TO_BEAN.toString(), new MysqlConvertJavaBean());
        convertMap.put(RenderSelectItem.TO_YAML.toString(), new PropertiesToYml());
        convertMap.put(RenderSelectItem.TO_PROPERTIES.toString(), new YmlToProperties());
    }


}
